package com.nowcoder.Offer.Tree;

import org.junit.Test;

/**
 * 判断是否为平衡二叉树
 */
public class IsBalanceTree {

    public boolean IsBalanced_Solution(TreeNode root) {
        if(root == null) return true;
        return Math.abs(getHeight(root.left) - getHeight(root.right)) <= 1
                && IsBalanced_Solution(root.left)
                && IsBalanced_Solution(root.right);
    }

    public int getHeight(TreeNode root){
        if(root == null) return 0;

        int leftDepth = getHeight(root.left);
        int rightDepth = getHeight(root.right);

        return Math.max(leftDepth,rightDepth) + 1;
    }

    @Test
    public void test(){
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        TreeNode node6 = new TreeNode(6);
        TreeNode node7 = new TreeNode(7);

        node1.left = node2; node1.right = node3;
        node2.left = node4; node2.right = node5;
        node3.left = node6; node3.right = node7;

        System.out.println(IsBalanced_Solution(node1));
    }


}
